package top.maof.book.controller;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import top.maof.book.annotation.Hot;
import top.maof.book.model.Chapter;
import top.maof.book.model.Role;
import top.maof.book.model.Web;
import top.maof.book.result.ApiResponse;
import top.maof.book.result.PageData;
import top.maof.book.result.PageWrap;
import top.maof.book.result.Result;
import top.maof.book.service.BookService;
import top.maof.book.service.ChapterService;
import top.maof.book.service.WebService;
import top.maof.book.spider.runtime.BookSpider;
import top.maof.book.utils.URLUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by CodeX4J.
 */
@Controller
@RequestMapping("/chapter")
@ResponseBody
@Slf4j
public class ChapterController {
    @Autowired
    private ChapterService chapterService;


    @ApiOperation("新建")
    @PostMapping("/create")
    @RequiresRoles({Role.ADMIN})
    public ApiResponse create(@RequestBody Chapter chapter) {
        return ApiResponse.success(chapterService.save(chapter));
    }

    @ApiOperation("根据ID删除")
    @GetMapping("/delete/{id}")
    @RequiresRoles({Role.ADMIN})
    public ApiResponse deleteById(@PathVariable Long id) {
        chapterService.removeById(id);
        return ApiResponse.success(null);
    }

    @ApiOperation("批量删除")
    @GetMapping("/delete/batch")
    @RequiresRoles({Role.ADMIN})
    public ApiResponse deleteByIdInBatch(@RequestParam String ids) {
        String [] idArray = ids.split(",");
        List<Long> idList = new ArrayList<>();
        for (String id : idArray) {
            idList.add(Long.valueOf(id));
        }
        chapterService.removeBatchByIds(idList);
        return ApiResponse.success(null);
    }

    @ApiOperation("根据ID修改")
    @PostMapping("/updateById")
    @RequiresRoles({Role.ADMIN})
    public ApiResponse updateById(@RequestBody Chapter chapter) {
        chapterService.updateById(chapter);
        return ApiResponse.success(null);
    }

    @ApiOperation("分页查询")
    @PostMapping("/page")
    public ApiResponse<PageData<Chapter>> findPage (@RequestBody PageWrap<Chapter> pageWrap) {
        return ApiResponse.success(chapterService.findPage(pageWrap));
    }

    @PostMapping("")
    @RequiresRoles(value = {Role.ADMIN})
    public Result add(Chapter chapter) throws Exception {
        if (chapterService.add(chapter) > 0) return Result.success();
        return Result.response_400();
    }

    @GetMapping("/{id}")
    public Result find(@PathVariable("id") int id) throws Exception {
        Chapter chapter = chapterService.find(id);
        if (chapter != null) return Result.success(chapter);
        return Result.response_400();
    }

    @PutMapping("")
    @RequiresRoles(value = {Role.ADMIN})
    public Result update(Chapter chapter) throws Exception {
        if (chapterService.update(chapter) > 0) return Result.success();
        return Result.response_400();
    }

    @DeleteMapping("/{id}")
    @RequiresRoles(value = {Role.ADMIN})
    public Result delete(@PathVariable("id") int id) throws Exception {
        if (chapterService.delete(id) > 0) return Result.success();
        return Result.response_400();
    }

    @Autowired
    BookSpider bookSpider;

    @Autowired
    WebService webService;

    @Autowired
    BookService bookService;

    @Hot(value = "#bookId")
    @GetMapping("/vo")
    public Result<Chapter> chapterVo(String url, Integer contentsId, Integer webId, Integer bookId) throws Exception {
        Chapter chapter = chapterService.findByUrl(url);
        //数据库没有,抓取
        if (chapter == null) {
            Web web = webService.find(webId);
            String url1 = URLUtils.changeDomain(web.getUrl(), url);
            chapter = bookSpider.chapter(url1, web);
            chapter.setContentsId(contentsId);
            // 完本小说就保存章节,连载不保存
            if ("完本".equals(bookService.find(bookId).getState()))
                chapterService.add(chapter);
            return Result.success(chapter);
        } else {
            return Result.success(chapter);
        }
    }
}
